﻿using System;
using System.IO;
using System.Text;
using Hematology.Data;
using HtmlAgilityPack;

namespace Hematology.Tools
{
	public class PageHelper
	{
		public static object[] EditorButtonSet
		{
			get
			{
				return new object[]
				       	{
				       		new object[] {"Undo", "Redo", "-", "NewPage", "Preview", "-", "Templates", "RemoveFormat"},
				       		new object[] {"Cut", "Copy", "Paste", "Image", "Table", "-", "Link", "Unlink", "Anchor", "-", "Print", "SpellChecker", "Scayt", "HorizontalRule"},
				       		new object[] {"Maximize", "ShowBlocks"},
				       		"/",
				       		new object[] {"Bold", "Italic", "Underline", "Strike", "-", "Subscript", "Superscript"},
				       		new object[] {"NumberedList", "BulletedList", "-", "Outdent", "Indent", "Blockquote", "CreateDiv"},
				       		new object[] {"JustifyLeft", "JustifyCenter", "JustifyRight", "JustifyBlock"},
				       		new object[] {"Find", "Replace"},
				       		"/",
				       		new object[] {"Styles", "Format", "Font", "FontSize", "-", "TextColor", "Source"}
				       	};
			}
		}

		public static string RemoveHtmlTags(string htmlText)
		{
			HtmlDocument doc = new HtmlDocument();
			doc.LoadHtml(htmlText);
			return doc.DocumentNode.InnerText;
		}

		public static string GetAttachIconClass(object oDocumentName)
		{
			if (oDocumentName != null)
			{
				string sDocumentName = oDocumentName.ToString();
				string extension = Path.GetExtension(sDocumentName);
				if (!String.IsNullOrEmpty(extension))
				{
					extension = extension.Trim('.');
					string[] fileTypes = {
					                     	"doc",
					                     	"docx",
					                     	"xls",
					                     	"xlsx",
					                     	"pdf",
					                     	"zip",
					                     	"rar",
					                     	"ppt",
					                     	"pptx"
					                     };

					if (Array.IndexOf(fileTypes, extension) >= 0)
						return String.Format("{0}ListIcon", extension);
				}
			}
			return "emptyListIcon";
		}

		public static string GetUserActivityIconClass(object oIsActivated)
		{
			if (oIsActivated != null && oIsActivated is Boolean)
				return Convert.ToBoolean(oIsActivated) ? "adminTableRowIconInactive" : "adminTableRowIconActive";
			return String.Empty;
		}

		public static string GetUserLockIconClass(object oIsLockedOut)
		{
			if (oIsLockedOut != null && oIsLockedOut is Boolean)
				return Convert.ToBoolean(oIsLockedOut) ? "adminTableRowIconLock" : "adminTableRowIconUnlock";
			return String.Empty;
		}

		public static string GetUserDetailsIconClass(object oIsActivated)
		{
			if (oIsActivated != null && oIsActivated is Boolean)
				return Convert.ToBoolean(oIsActivated) ? "adminTableRowDetailsIconActive" : "adminTableRowDetailsIconInactive";
			return String.Empty;
		}

		public static string GetRoundedFileSize(object oDocumentSize)
		{
			if (oDocumentSize != null && oDocumentSize is Int32)
			{
				int iDocumentSize = Convert.ToInt32(oDocumentSize);

				if (iDocumentSize < 1024)
					return String.Format("{0} b", iDocumentSize);

				if (iDocumentSize > 1024 && iDocumentSize < 1024 * 1024)
					return String.Format("{0:0.00} Kb", iDocumentSize / 1024f);

				if (iDocumentSize > 1024 * 1024)
					return String.Format("{0:0.00} Mb", iDocumentSize / 1024f / 1024f);
			}

			return Helper.resWhitespace;
		}

		public static string SetDateCellContent(object oDateValue)
		{
			return (oDateValue != null && oDateValue is DateTime)
					? Convert.ToDateTime(oDateValue).ToShortDateString()
					: Helper.resWhitespace;
		}

		public static string GetEventTitleExtended(object oEventId)
		{
			if (oEventId != null && oEventId is Int32)
			{
				SiteEvent siteEvent = SiteEvent.Get(Convert.ToInt32(oEventId));
				if (siteEvent != null)
				{
					string sEventTypeName = EnumHelper.GetEventTypeName(siteEvent.EventTypeCode);
					if (!String.IsNullOrEmpty(sEventTypeName))
					{
						SiteEventType siteEventType = SiteEventType.GetSiteEventTypeByCode(siteEvent.EventTypeCode);
						if (siteEventType != null)
						{
							string sEventNavigateUrl = String.Format("<a href=\"/Events.aspx?et={0}&id={1}\">{2}</a>", sEventTypeName, siteEvent.EventId, siteEvent.Title);

							return String.Format("{0} (<a class=\"internalRecentLink\" href=\"/Events.aspx?et={1}\">{2}</a>)", sEventNavigateUrl, sEventTypeName, siteEventType.Name.ToLower());
						}
					}
				}
			}
			return String.Empty;
		}

		public static string GetEventTitle(object oEventId, object oTitle, EnumHelper.EventType etCurrentEventType)
		{
			return (oEventId != null && oTitle != null)
					? String.Format("<a href=\"/Events.aspx?et={0}&id={1}\">{2}</a>", etCurrentEventType, oEventId, oTitle)
					: String.Empty;
		}

		public static string GetCroppedUserName(object oFirstName, object oMiddleName, object oLastName)
		{
			if (!String.IsNullOrEmpty(oFirstName.ToString()) && !String.IsNullOrEmpty(oLastName.ToString()))
			{
				return !String.IsNullOrEmpty(oMiddleName.ToString())
						? String.Format("{0} {1}. {2}.", oLastName, oFirstName.ToString()[0], oMiddleName.ToString()[0])
						: String.Format("{0} {1}", oLastName, oFirstName);
			}
			return Helper.resWhitespace;
		}

		public static string FormatEmailString(object oFirstName, object oMiddleName, object oLastName, object oEmail)
		{
			if (!String.IsNullOrEmpty(oFirstName.ToString()) && !String.IsNullOrEmpty(oLastName.ToString()) && !String.IsNullOrEmpty(oEmail.ToString()))
			{
				return !String.IsNullOrEmpty(oMiddleName.ToString())
						? String.Format("mailto:{0}%20{1}.%20{2}.&lt;{3}&gt;", oLastName, oFirstName.ToString()[0], oMiddleName.ToString()[0], oEmail)
						: String.Format("mailto:{0}%20{1}&lt;{2}&gt;", oLastName, oFirstName, oEmail);
			}
			return Helper.resWhitespace;
		}

		public static string GetEventShortDateRange(object oStartDate, object oFinishDate)
		{
			string sFromDate = String.Empty;
			string sTillDate = String.Empty;

			if (oStartDate != null)
				sFromDate = Convert.ToDateTime(oStartDate).ToShortDateString();

			if (oFinishDate != null)
				sTillDate = Convert.ToDateTime(oFinishDate).ToShortDateString();

			return (oStartDate == null && oFinishDate == null)
					? String.Empty
					: String.Format("{0} {1} {2}",
									Helper.resEventDate,
									!String.IsNullOrEmpty(sFromDate) ? String.Format("с <b>{0}</b>", sFromDate) : String.Empty,
									!String.IsNullOrEmpty(sTillDate) ? String.Format("до <b>{0}</b>", sTillDate) : String.Empty);
		}

		public static bool GetEventProperiesPanelVisible(object oStartDate, object oFinishDate, object oEventPlace)
		{
			return oStartDate != null || oFinishDate != null || !String.IsNullOrEmpty(oEventPlace.ToString());
		}

		public static string GetTeaser(object oFullString)
		{
			string sFullString = oFullString.ToString();
			if (String.IsNullOrEmpty(sFullString))
				return String.Empty;

			sFullString = RemoveHtmlTags(sFullString);

			StringBuilder sb = new StringBuilder();
			int iSearchWords = ConfigReader.TeaserWordsCount;

			string[] fullStringWords = sFullString.Split(new[]
			                                             	{
			                                             		Convert.ToChar(Helper.resSpace)
			                                             	});

			for (int i = 0; i < (fullStringWords.Length < iSearchWords ? fullStringWords.Length : iSearchWords); i++)
			{
				sb.AppendFormat("{0} ", fullStringWords[i]);
			}
			sb.Remove(sb.Length - 1, 1);

			sb.Append(Helper.resThreeDots);
			return sb.ToString();
		}

		public static string GetSearchTeaser(SiteContent siteContent, string sSearchText)
		{
			StringBuilder sbTeaser = new StringBuilder();
			int iSearchWords = ConfigReader.SearchTeaserWrapperWordsCount;

			string sClearSiteContent = RemoveHtmlTags(siteContent.Content);

			string sSearchTextOriginal =
				sClearSiteContent.Substring((sClearSiteContent.ToLower().IndexOf(sSearchText.ToLower())), sSearchText.Length);

			string sStringMatch = sClearSiteContent.Substring((sClearSiteContent.ToLower().IndexOf(sSearchText.ToLower())), sSearchText.Length + 1);
			bool bIsSpaceAfter = Char.IsWhiteSpace(sStringMatch[sStringMatch.Length - 1]);

			string[] resultParts = sClearSiteContent.Split(new[]
			                                               	{
			                                               		sSearchTextOriginal
			                                               	}, StringSplitOptions.RemoveEmptyEntries);

			string sResultBefore = resultParts[0];
			

			if (!String.IsNullOrEmpty(sResultBefore))
			{
				string[] resultBeforeWords = sResultBefore.Split(new[]
				                                                 	{
				                                                 		Convert.ToChar(Helper.resSpace)
				                                                 	});

				bool bIsStringStart = resultBeforeWords.Length < iSearchWords;

				if (!bIsStringStart)
					sbTeaser.Append(Helper.resThreeDots);

				for (int i = resultBeforeWords.Length - (bIsStringStart ? resultBeforeWords.Length : iSearchWords); i < resultBeforeWords.Length; i++)
				{
					sbTeaser.AppendFormat("{0} ", resultBeforeWords[i]);
				}
				sbTeaser.Remove(sbTeaser.Length - 1, 1);
			}

			if (sbTeaser.Length != 0)
			{
				sbTeaser.AppendFormat("<b>{0}</b>", sSearchTextOriginal);
				if (bIsSpaceAfter)
					sbTeaser.Append(Helper.resSpace);
			}

			// = ;
			if (!String.IsNullOrEmpty(resultParts[1]))
			{
				string sResultAfter = sClearSiteContent.Substring(sClearSiteContent.IndexOf(resultParts[1]));
				string[] resultAfterWords = sResultAfter.Split(new[]
				                                               	{
				                                               		Convert.ToChar(Helper.resSpace)
				                                               	});

				for (int i = 0; i < (resultAfterWords.Length < iSearchWords ? resultAfterWords.Length : iSearchWords); i++)
				{
					sbTeaser.AppendFormat("{0} ", resultAfterWords[i]);
				}
				sbTeaser.Remove(sbTeaser.Length - 1, 1);

				bool bIsStringEnd = resultAfterWords.Length < iSearchWords;

				if (!bIsStringEnd)
					sbTeaser.Append(Helper.resThreeDots);
			}

			return sbTeaser.ToString();
		}

		public static string GetDeleteProfileActionString(object oSiteUser)
		{
			if (oSiteUser is SiteUserExtended)
			{
				SiteUserExtended siteUser = (SiteUserExtended)oSiteUser;

				if (!siteUser.BaseInfo.IsActivated.HasValue || !siteUser.BaseInfo.IsLockedOut.HasValue)
					throw new Exception("Невозможно получить данные о состоянии удаляемого пользователя");

				return String.Format("return confirm('{0}: {1} ({2} {3} {4})')",
									 Helper.resConfrmUserDelete,
									 siteUser.BaseInfo.Email,
									 siteUser.LastName,
									 siteUser.FirstName,
									 siteUser.MiddleName);
			}
			throw new Exception("Невозможно получить данные об удаляемом пользователе");
		}

		public static string GetConfirmProfileActionString(object oSiteUser, bool bIsActivationAction)
		{
			if (oSiteUser is SiteUserExtended)
			{
				SiteUserExtended siteUser = (SiteUserExtended) oSiteUser;

				if (!siteUser.BaseInfo.IsActivated.HasValue || !siteUser.BaseInfo.IsLockedOut.HasValue)
					throw new Exception("Невозможно получить данные о состоянии изменяемого пользователя");

				string sResourceProfileActionString = bIsActivationAction
				                                      	? siteUser.BaseInfo.IsActivated.Value
				                                      	  	? Helper.resConfirmUserDeactivation
				                                      	  	: Helper.resConfirmUserActivation
				                                      	: siteUser.BaseInfo.IsLockedOut.Value
				                                      	  	? Helper.resConfirmUserUnlock
				                                      	  	: Helper.resConfirmUserLock;


				return String.Format("return confirm('{0}: {1} ({2} {3} {4})')",
				                     sResourceProfileActionString,
				                     siteUser.BaseInfo.Email,
				                     siteUser.LastName,
				                     siteUser.FirstName,
				                     siteUser.MiddleName);
			}
			throw new Exception("Невозможно получить данные об изменяемом пользователе");
		}

		public static string GetAttachIconToolTip(object oFileAttachementsCount)
		{
			return String.Format("{0}: {1}", Helper.resAttachedFiles, oFileAttachementsCount);
		}

		public static string GetInternalDocumentsIconToolTip(object oChildSiteContentCount)
		{
			return String.Format("{0}: {1}", Helper.resInternalDocuments, oChildSiteContentCount);
		}
	}
}